package com.gitee.ywj1352.zk.quickStart;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * @author wenjie.yang on 2019/6/19.
 */
public class WatcherDemo {
    public static void main(String[] args) throws Exception {

        ZooKeeper connection = QuickStart.createConnection();
        connection.create("/zk-persis-ywj","1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //exits,getData,getChildren
        //watcher 只生效一次
        Stat stat = connection.exists("/zk-persis-ywj", watchedEvent ->{
                    System.out.println(watchedEvent.getType() + " ->" + watchedEvent.getPath());
                    try {
                        connection.exists(watchedEvent.getPath(),true);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        //通过修改事务来触发 监听
        Stat stat1 = connection.setData("/zk-persis-ywj", "2".getBytes(), stat.getVersion());

        Thread.sleep(100);

        connection.delete("/zk-persis-ywj",stat1.getVersion());

        System.in.read();
    }


}
